package com.yyw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.common.constant.product.enums.SpuInfoEnum;
import com.yyw.common.to.productsearch.AttrTo;
import com.yyw.common.utils.PageUtils;
import com.yyw.common.utils.Query;
import com.yyw.gulimall.product.dao.ProductAttrValueDao;
import com.yyw.gulimall.product.entity.AttrEntity;
import com.yyw.gulimall.product.entity.ProductAttrValueEntity;
import com.yyw.gulimall.product.service.AttrService;
import com.yyw.gulimall.product.service.ProductAttrValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrTo> getAttrToBySpuId(Long spuId) {
        List<ProductAttrValueEntity> productAttrList = this.list(new QueryWrapper<ProductAttrValueEntity>()
                .lambda().eq(ProductAttrValueEntity::getSpuId, spuId));
        List<Long> attrIds = productAttrList.stream().map(e -> e.getAttrId()).collect(Collectors.toList());
        List<AttrEntity> attrEntities = attrService.listByIds(attrIds);
        if (CollectionUtils.isEmpty(attrEntities)) {
            return null;
        }
        Map<Long, String> map = attrEntities.stream()
                .filter(e -> Objects.equals(SpuInfoEnum.YES_SEARCH.getCode(), e.getSearchType()))
                .collect(Collectors.toMap(AttrEntity::getAttrId, e -> e.getAttrName()));

        List<AttrTo> attrTos = productAttrList.stream().filter(e -> !Objects.equals(null, map.get(e.getAttrId())))
                .map(e -> {
                    AttrTo to = new AttrTo();
                    to.setAttrId(e.getAttrId());
                    to.setAttrName(e.getAttrName());
                    to.setAttrValue(e.getAttrValue());
                    return to;
                }).collect(Collectors.toList());
        return attrTos;
    }

}